import java.util.ArrayList;
import java.util.List;

public class _1765 {
    static class Solution {
        public int[][] highestPeak(int[][] isWater) {
            int m = isWater.length;
            int n = isWater[0].length;
            boolean[][] v = new boolean[m][n];
            int[][] res = new int[m][n];
            List<int[]> cur = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (isWater[i][j] == 1) {
                        cur.add(new int[]{i, j});
                        v[i][j] = true;
                    }
                }
            }
            int step = 0;
            int[][] dirs = {
                    {0, 1},
                    {0, -1},
                    {1, 0},
                    {-1, 0}
            };
            while (cur.size() > 0) {
                List<int[]> next = new ArrayList<>();
                for (int[] node : cur) {
                    int r = node[0];
                    int c = node[1];
                    res[r][c] = step;
                    for (int[] dir : dirs) {
                        int nr = r + dir[0];
                        int nc = c + dir[1];
                        if (nr < 0 || nc < 0 || nr >= m || nc >= n || v[nr][nc]) {
                            continue;
                        }
                        v[nr][nc] = true;
                        next.add(new int[]{nr, nc});
                    }
                }
                step++;
                cur = next;
            }
            return res;
        }
    }
}
